package com.lang.downloader.http.Interceptor;

import com.lang.downloader.http.header.HttpRequestHeader;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.Map;
import java.util.Set;

/**
 * 设置请求头
 */
public class HttpRequestHeaderInterceptor implements Interceptor {

    private final HttpRequestHeader requestHeader;

    public HttpRequestHeaderInterceptor(HttpRequestHeader requestHeader) {
        this.requestHeader = requestHeader;
    }

    @NotNull
    @Override
    public Response intercept(@NotNull Chain chain) throws IOException {
        Request request = chain.request();
        if (requestHeader == null)
            return chain.proceed(request);
        Request.Builder builder = request.newBuilder();
        Set<Map.Entry<String, String>> headers = requestHeader.headers();
        if (headers != null && !headers.isEmpty()) {
            for (Map.Entry<String, String> header : headers) {
                builder.addHeader(header.getKey(), header.getValue());
            }
        }
        return chain.proceed(builder.build());
    }
}
